package com.chu.seviece.impl;

import com.chu.bean.Grade;
import com.chu.bean.Student;
import com.chu.dao.GradeDao;
import com.chu.dao.StudentDao;
import com.chu.seviece.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private GradeDao gradeDao;

    //        增加学生和年级
    @Override
    @Transactional
    public int insert(Grade grade, Student student) {
        try {
            //先新增年级
            Grade grade1 = gradeDao.save(grade);
            //新增年级
            student.setGrade(grade1);
            studentDao.save(student);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }
    //主键查询学生信息;;顺带查询多方（年级）
    @Override
    public Student findOneStudent(int id) {
        return studentDao.findOne(id);
    }
    //主键查询年级信息；；顺带查询一方（学生）
    @Override
    public Grade findOneGrade(int id) {
        return gradeDao.findOne(id);
    }
    //已知条件：年级编号 查询年级的学生信息
    @Override
    public List<Student> findByGrade_GradeId(int id) {
        return studentDao.findByGrade_GradeId(id);
    }



    //根据主键ID查询学生信息 (自定义hql语句)
    @Override
    //hql语法和sql语法一致 但是需要将表名换成类名 列名换成属性名 区分大小写
    //hql查询全部列的时候 要直接用 from 类名
    public Student findStudentById(int id) {
        return studentDao.findStudentById(id);
    }



    //根据主键ID和学生姓名查询学生信息(自定义hql语句)
    @Override
    public Student findStudentByIdAndName(int id,String name) {
        return studentDao.findStudentByIdAndName(id, name);
    }
    //根据主键ID和学生姓名查询学生信息(自定义hql语句)
    @Override
    public Student findStudentByIdName(int id, String name) {
        return studentDao.findStudentByIdName(id, name);
    }
    //关联查询
    //根据年级id查询学生列表
    @Override
    public List<Student> getStudentMakeGradeId(int id) {
        return studentDao.getStudentMakeGradeId(id);
    }
    //用SQL 查询 需要指定nativeQuery=true;;指定value为查询的SQL语句
    @Override
    public List<Student> findAllStudent() {
        return studentDao.findAllStudent();
    }

    //Modifying 注解通知springData 是一个 update或者delete 操作
    @Override
    @Transactional
    public int updateStudentById(String name, int id) {
        return studentDao.updateStudentById(name, id);
    }


}
